package com.mgg.user.service.user.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

import com.mgg.common.client.message.MessageClient;
import com.mgg.common.dao.DaoSupport;
import com.mgg.common.exception.ServiceException;
import com.mgg.common.entity.UserDO;
import com.mgg.user.enums.UserResultEnum;
import com.mgg.user.service.BaseUserService;
import com.mgg.user.service.user.UserActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service("userActivityService")
public class UserActivityServiceImpl implements UserActivityService{

	@Autowired
	private DaoSupport dao;

	@Autowired
    @Qualifier("poolTaskExecutor")
    private Executor executor;
	
	@Autowired
	private MessageClient messageClient;
	
	@Autowired
	private BaseUserService baseUserService;
	
	@Override
	public Integer updateActCode(String sender, String shopCode, String actCode, String old_status, String new_status, String userId, String phone, String actTime){
		Map<String,String> updateMap = new HashMap<>();
		updateMap.put("shop_code", shopCode);
		updateMap.put("act_code", actCode);
		updateMap.put("phone", phone);
		updateMap.put("user_id", userId);
		updateMap.put("sender", sender);
		updateMap.put("act_time", actTime);
		updateMap.put("old_status", old_status);
		updateMap.put("new_status", new_status);
		return dao.save("UserActivityMapper.updateActCode", updateMap);
	}

	@Override
	public Map<String, String> getActCodeInfo(String code) {
		Map<String,String> result = (Map<String, String>) dao.findForObject("UserActivityMapper.getActCodeInfo", code);
		return result;
	}

	/**
	 * 发送激活码
	 */
	@Override
	public void sendActCode(String userId, Integer giveNum) {
		UserDO user = baseUserService.getUserByUserId(userId);
		String shopCode = user.getShopCode();
		for (int i = 0; i < giveNum; i++) {
			String actCode = null;
			int count = 0;
			do {			
				if (count > 50) {
					throw new ServiceException(UserResultEnum.ACTCODE_SEND_FAIL.getCode(), UserResultEnum.ACTCODE_SEND_FAIL.getMessage());
				}
				count++;
				actCode = (String) dao.findForObject("UserActivityMapper.getUnSendActCode", null);
			} while (updateActCode(userId, shopCode, actCode, "0", "1", null, null, null) == 0);
			
			//发送短信
			String code = actCode;
			CompletableFuture
			.runAsync(() -> {
				String page = "activeShop";
                messageClient.sendShopActCode(userId,code,page);
			}, executor);
		}
	}
}
